package com.example.myapplication.Network;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.Inet4Address;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetAction {
    /**
     * 获取当前连接的Wi-Fi IP地址（仅限IPv4）
     *
     * @param context 上下文
     * @return IP地址字符串，如果获取失败则返回null
     */
    @SuppressLint("DefaultLocale")
    public static String getWifiIPAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            return null;
        }

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null) {
            return null;
        }

        int ipAddress = wifiInfo.getIpAddress();

        // 将int转换为IP地址的字符串形式
        // 注意：这里只处理了IPv4的情况
//        String hex = Integer.toHexString(ipAddress & 0xFF);
//        if (hex.length() == 1) {
//            hex = '0' + hex;
//        }
//        final String ip = String.valueOf(ipAddress & 0xFF |
//                (ipAddress >> 8 & 0xFF) << 8 |
//                (ipAddress >> 16 & 0xFF) << 16 |
//                (ipAddress >> 24 & 0xFF) << 24);
//
//        return ip;
        // 返回的IP地址是整数形式的字符串，需要转换为点分十进制形式
        String res =   String.format(
                "%d.%d.%d.%d",
                (ipAddress & 0xff),
                (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff),
                (ipAddress >> 24 & 0xff)
        );
        return res;
    }

    public static String brocastAddress(Context context){
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            return null;
        }

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null) {
            return null;
        }

        int ipAddress = wifiInfo.getIpAddress();
        // 获取网络前缀长度
        int prefixLength = getIpAddrMaskLenForInterfaces();
        int mask = 0xffffffff <<  prefixLength;
        //获取广播地址
        int brocastAddress = ipAddress | mask;

        String res =   String.format(
                "%d.%d.%d.%d",
                (brocastAddress & 0xff),
                (brocastAddress >> 8 & 0xff),
                (brocastAddress >> 16 & 0xff),
                (brocastAddress >> 24 & 0xff)
        );
        return res;
    }

    private static int getIpAddrMaskLenForInterfaces() {
        try {
            Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();    //获取本机所有的网络接口
            while (networkInterfaceEnumeration.hasMoreElements()) { //判断 Enumeration 对象中是否还有数据
                NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); //获取 Enumeration 对象中的下一个数据
//                && !interfaceName.equals(networkInterface.getDisplayName())
                if (!networkInterface.isUp() ) { //判断网口是否在使用，判断是否时我们获取的网口
                    continue;
                }

                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {    //
                    if (interfaceAddress.getAddress() instanceof Inet4Address) {    //仅仅处理ipv4
                        if (networkInterface.getName().startsWith("wlan")) {  // wifi类型的
//                            return calcMaskByPrefixLength(interfaceAddress.getNetworkPrefixLength());
                            return interfaceAddress.getNetworkPrefixLength();
                        }
                         //获取掩码位数，通过 calcMaskByPrefixLength 转换为字符串
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return -1;
    }

    //通过子网掩码的位数计算子网掩码
    public static String calcMaskByPrefixLength(int length) {

        int mask = 0xffffffff << (32 - length);
        int partsNum = 4;
        int bitsOfPart = 8;
        int maskParts[] = new int[partsNum];
        int selector = 0x000000ff;

        for (int i = 0; i < maskParts.length; i++) {
            int pos = maskParts.length - 1 - i;
            maskParts[pos] = (mask >> (i * bitsOfPart)) & selector;
        }

        String result = "";
        result = result + maskParts[0];
        for (int i = 1; i < maskParts.length; i++) {
            result = result + "." + maskParts[i];
        }
        return result;
    }
}
